from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware

from common.exception.biz_exception import BizException
from common.response.biz_response import R
from router.sys import auth_router, user_router
from util.yaml_util import load_yaml_config

SECRET_KEY = load_yaml_config('config/session.yaml', "session", "secret_key")

app = FastAPI()

# 添加Session中间件，用于管理用户会话
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)  # type: ignore

# 添加CORS中间件，允许跨域请求
# origins参数指定允许的源列表，可以是具体的域名或"*"表示允许所有源
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"],  # type: ignore
                   allow_headers=["*"])
# 添加权限相关路由
app.include_router(auth_router.router, prefix="/auth")
app.include_router(user_router.router, prefix="/user")


# 处理业务异常
@app.exception_handler(BizException)
async def biz_exception_handler(_: Request, biz_exception: BizException) -> JSONResponse:
    response_data = R.failed(biz_exception)
    return JSONResponse(content=response_data.__dict__)
